<template>
  <div
    class="year-range-select"
    style="width: 210px; display: flex; align-items: center"
  >
    <el-date-picker
      :clearable="false"
      :editable="false"
      v-model="comBegin"
      type="year"
      value-format="YYYY"
      :disabled-date="disabledBegin"
    />
    <span style="margin: 0 10px">至</span>
    <el-date-picker
      :clearable="false"
      :editable="false"
      v-model="comEnd"
      type="year"
      value-format="YYYY"
      :disabled-date="disabledEnd"
    />
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
const emit = defineEmits(['update:begin', 'update:end'])
const props = defineProps({
  begin: {
    type: String,
    default: dayjs().format('YYYY')
  },
  end: {
    type: String,
    default: dayjs().format('YYYY')
  }
})
const comBegin = computed({
  get(val) {
    return props.begin
  },
  set(val) {
    //  如果截止年份 - 选中年份 > 3年 需要重置截止年份
    //
    if (dayjs(comEnd.value).subtract(2, 'year').isAfter(dayjs(val))) {
      comEnd.value = val
    }
    // 如果选中年份 > 截止年份
    else if (dayjs(val).isAfter(dayjs(comEnd.value))) {
      comEnd.value = val
    }
    if (val) {
      emit('update:begin', val)
    } else {
      emit('update:begin', '')
    }
  }
})
const comEnd = computed({
  get(val) {
    return props.end
  },
  set(val) {
    if (val) {
      emit('update:end', val)
    } else {
      emit('update:end', '')
    }
  }
})
const disabledBegin = date => {
  if (dayjs(date).isAfter(dayjs())) {
    return true
    //   } else if (dayjs(date).isBefore(dayjs(comEnd.value).subtract(2, 'year'))) {
    //     return true
    //   }
  }
  return false
}
const disabledEnd = date => {
  if (dayjs(date).isAfter(dayjs())) {
    return true
  } else if (dayjs(date).isAfter(dayjs(comBegin.value).add(2, 'year'))) {
    return true
  } else if (dayjs(date).isBefore(dayjs(comBegin.value))) {
    return true
  }
  return false
}
</script>
<style lang="scss" scoped></style>
